package com.gateio.flutter.lib_furnace.container

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import com.gateio.flutter.lib_furnace.AnimationType
import com.gateio.flutter.lib_furnace.GTFlutter
import com.gateio.flutter.lib_furnace.GTFlutterInitializer
import com.gateio.flutter.lib_furnace.R
import com.gateio.flutter.lib_furnace.protocol.IGTFlutterHostDelegate
import com.gateio.flutter.lib_furnace.util.GTFurnaceConstant
//import com.gateio.rxjava.basemvp.IHostView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
//import com.trello.rxlifecycle4.LifecycleTransformer
//import com.trello.rxlifecycle4.RxLifecycle
//import com.trello.rxlifecycle4.android.ActivityEvent
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
//import io.reactivex.rxjava3.core.Observable
//import io.reactivex.rxjava3.core.ObservableTransformer
//import io.reactivex.rxjava3.subjects.BehaviorSubject

/**
 * Author: Shper
 * Created: 2023/6/12
 */
//open class GTFlutterFragmentActivity : FlutterFragmentActivity(), IHostView {
open class GTFlutterFragmentActivity : FlutterFragmentActivity() {
    companion object {
        fun withCachedEngineId(cachedEngineId: String) = GTCachedEngineIntentBuilder(GTFlutterFragmentActivity::class.java, cachedEngineId)
    }

    private var hostDelegate: IGTFlutterHostDelegate? = null
    private var animationType: AnimationType = AnimationType.rightInRightOut
    private var routerName: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d("GTFlutter", "$this - onCreate")
        // 判断 FlutterEngineCache 不包含需要的 FlutterEngine时，重新创建 Flutter 引擎
        val transparentStatusBar = intent.getBooleanExtra(GTFurnaceConstant.KEY_TRANSPARENT_STATUS_BAR, true)
        val customEngineId = intent.getStringExtra(GTFurnaceConstant.KEY_CUSTOM_ENGINE_ID) ?: ""
        routerName = intent.getStringExtra(GTFurnaceConstant.KEY_ROUTER_NAME) ?: ""
        val engineId: String = customEngineId.ifBlank { cachedEngineId ?: routerName }
        AnimationType.valueOf(
            intent.getStringExtra(GTFurnaceConstant.KEY_ANIMATION_TYPE)
                ?: AnimationType.rightInRightOut.name
        ).let {
            animationType = it
        }

        if (!FlutterEngineCache.getInstance().contains(engineId)) {
            Log.w("GTFlutter", "$this -  flutterEngineCache is not contains $engineId")
            val routeParams = intent.getStringExtra(GTFurnaceConstant.KEY_ROUTER_PARAMS) ?: "{}"
            val routeParamMap: HashMap<String, Any> = Gson().fromJson(routeParams, object : TypeToken<HashMap<String, Any>>() {}.type)
            GTFlutter.createAndRunEngine(this, routerName, routeParamMap, engineId, transparentStatusBar)
        }

        hostDelegate = GTFlutterInitializer.getHostDelegate()

        super.onCreate(savedInstanceState)
        // 转场动画
        launchAnimation()

        hostDelegate?.onCreate(this, true)
        hostDelegate?.setupStatusBarAndNavigationBarStyle(this, transparentStatusBar)
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        Log.d("GTFlutter", "$this -  configureFlutterEngine")
        super.configureFlutterEngine(flutterEngine)
        hostDelegate?.configureFlutterEngine(this, true, flutterEngine)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        Log.d("GTFlutter", "$this -  onConfigurationChanged")
        super.onConfigurationChanged(newConfig)
        hostDelegate?.onConfigurationChanged(this, true, newConfig)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        Log.d("GTFlutter", "$this -  onActivityResult")
        super.onActivityResult(requestCode, resultCode, data)
        hostDelegate?.onActivityResult(this, true, requestCode, resultCode, data)
    }

    override fun onStart() {
        Log.d("GTFlutter", "$this -  onStart")
        super.onStart()
        hostDelegate?.onStart(this)
    }

    override fun onRestart() {
        Log.d("GTFlutter", "$this -  onRestart")
        hostDelegate?.onRestart(this)
        super.onRestart()
    }

    override fun onResume() {
        Log.d("GTFlutter", "$this -  onResume")
        hostDelegate?.onResume(this)
        super.onResume()
    }

    override fun onStop() {
        Log.d("GTFlutter", "$this -  onStop")
        hostDelegate?.onStop(this)
        super.onStop()
    }

    override fun finish() {
        Log.d("GTFlutter", "$this -  finish")
        hostDelegate?.finish(this)
        super.finish()
        // 转场动画
        finishAnimation()
    }

    override fun onDestroy() {
        Log.d("GTFlutter", "$this -  onDestroy")
        hostDelegate?.onDestroy(this)
        super.onDestroy()
        GTFlutter.pageStartedList.remove(routerName)
    }

    // Transition Animation
    fun launchAnimation() {
        when (animationType) {
            AnimationType.noAnimation -> overridePendingTransition(0, 0)
            AnimationType.rightInRightOut -> overridePendingTransition(R.anim.furnace_right_in, R.anim.furnace_left_out)
            AnimationType.leftInLeftOut -> overridePendingTransition(R.anim.furnace_left_in, R.anim.furnace_right_out)
        }
    }

    fun finishAnimation() {
        when (animationType) {
            AnimationType.noAnimation -> overridePendingTransition(0, 0)
            AnimationType.rightInRightOut -> overridePendingTransition(R.anim.furnace_left_in, R.anim.furnace_right_out)
            AnimationType.leftInLeftOut -> overridePendingTransition(R.anim.furnace_right_in, R.anim.furnace_left_out)
        }
    }

    // IHostView
//    override fun getHost(): Activity {
//        return this
//    }

//    override fun isActive(): Boolean {
//        return true
//    }
//
//    override fun showToast(msg: String?) {
//        hostDelegate?.showToast(this, msg)
//    }

//    override fun showToast(resId: Int) {
//        hostDelegate?.showToast(this, resId)
//    }
//
//    override fun showLoadingProgress() {
//        hostDelegate?.showLoadingProgress(this)
//    }
//
//    override fun dismissLoadingProgress() {
//        hostDelegate?.dismissLoadingProgress(this)
//    }
//
//    override fun isNetWorkConnected(): Boolean {
//        return hostDelegate?.isNetWorkConnected(this) ?: false
//    }

//    override fun logOut() {
//        hostDelegate?.logOut(this)
//    }
//
//    override fun showPassDialog(type: Int, msg: String?) {
//        hostDelegate?.showPassDialog(this, type, msg)
//    }
//
//    override fun showSecondPassDialog(msg: String?) {
//        hostDelegate?.showSecondPassDialog(this, msg)
//    }
//
//    override fun showSetFundPassTip(msg: String?) {
//        hostDelegate?.showSetFundPassTip(this, msg)
//    }
//
//    override fun showFingerPrintDialog(qrid: String?) {
//        hostDelegate?.showFingerPrintDialog(this, qrid)
//    }
//
//    // 无需实现废弃
//    override fun showMomentTokenException() {
//        // ignore
//    }
//
//    override fun bindFragment(TAG: String?, baseFragment: Fragment?) {
//        // ignore
//    }

//    override fun unbindFragment(TAG: String?) {
//        // ignore
//    }
//
//    override fun <F : Fragment?> getFragmentByTag(TAG: String?, fClass: Class<F>?): F? {
//        // ignore
//        return null
//    }
//
//    override fun <F : Fragment?> getFragmentByClass(fClass: Class<F>?): F? {
//        // ignore
//        return null
//    }

    // 临时实现 rxjava 和
//    var rxLifecycleSubject: BehaviorSubject<ActivityEvent> = BehaviorSubject.create()

//    override fun lifecycle(): Observable<ActivityEvent> {
//        return rxLifecycleSubject.hide()
//    }

//    override fun <T : Any?> bindUntilEvent(event: ActivityEvent): LifecycleTransformer<T> {
//        return RxLifecycle.bindUntilEvent(rxLifecycleSubject, event)
//    }
//
//    override fun <T : Any?> bindToLifecycle(): LifecycleTransformer<T> {
//        return RxLifecycle.bindUntilEvent(rxLifecycleSubject, ActivityEvent.DESTROY)
//    }

    @Suppress(
        "UPPER_BOUND_VIOLATED_BASED_ON_JAVA_ANNOTATIONS",
        "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS", "WRONG_NULLABILITY_FOR_JAVA_OVERRIDE"
    )
//    override fun <T : Any> bindToActiveChanged(): ObservableTransformer<T, T> {
//        return ObservableTransformer { upstream: Observable<T> -> upstream }
//    }

    /**
     * 获取 Flutter 引擎Id
     */
    fun getEngineId(): String? {
        return cachedEngineId
    }

    class GTCachedEngineIntentBuilder(
        activityClass: Class<out GTFlutterFragmentActivity>,
        cachedEngineId: String
    ) : CachedEngineIntentBuilder(activityClass, cachedEngineId) {

        private var routerName: String? = null
        private var routeParams: String? = null
        private var customEngineId: String = ""
        private var transparentStatusBar: Boolean = true
        private var animationType: AnimationType = AnimationType.rightInRightOut
        private var dialogEnableLandscape: Boolean = false

        fun routerName(routerName: String): GTCachedEngineIntentBuilder {
            this.routerName = routerName
            return this
        }

        fun routeParams(routeParams: Map<String, Any>?): GTCachedEngineIntentBuilder {
            routeParams?.let {
                this.routeParams = Gson().toJson(it)
            }
            return this
        }

        fun customEngineId(customEngineId: String): GTCachedEngineIntentBuilder {
            this.customEngineId = customEngineId
            return this
        }

        fun transparentStatusBar(transparentStatusBar: Boolean): GTCachedEngineIntentBuilder {
            this.transparentStatusBar = transparentStatusBar
            return this
        }

        fun animationType(animationType: AnimationType): GTCachedEngineIntentBuilder {
            this.animationType = animationType
            return this
        }

        fun dialogEnableLandscape(dialogEnableLandscape: Boolean): GTCachedEngineIntentBuilder {
            this.dialogEnableLandscape = dialogEnableLandscape
            return this
        }

        override fun build(context: Context): Intent {
            val intent = super.build(context)
            intent.putExtra(GTFurnaceConstant.KEY_ROUTER_NAME, routerName)
            intent.putExtra(GTFurnaceConstant.KEY_ROUTER_PARAMS, routeParams)
            intent.putExtra(GTFurnaceConstant.KEY_CUSTOM_ENGINE_ID, customEngineId)
            intent.putExtra(GTFurnaceConstant.KEY_TRANSPARENT_STATUS_BAR, transparentStatusBar)
            intent.putExtra(GTFurnaceConstant.KEY_ANIMATION_TYPE, animationType.name)
            intent.putExtra(GTFurnaceConstant.KEY_DIALOG_ENABLE_LANDSCAPE, dialogEnableLandscape)
            return intent
        }
    }
}